// ctx扩展
const jwt = require("jsonwebtoken");
const crypto = require("crypto");
const fs = require("fs");
// 商户密钥
const privateKey = fs.readFileSync("./config/apiclient_key.pem");
module.exports = {
  // 自定义接口结构
  send(payload) {
    // 这里的this即为ctx
    this.body = {
      success: true,
      code: 200,
      ...payload,
    };
    this.status = payload.code || 200;
  },
  // 返回token
  generateToken(_id) {
    const { secret, expiresIn } = this.app.config.jwt;
    return jwt.sign({ id: _id }, secret, { expiresIn });
  },
  // 生成商户订单号
  generateOutTradeNo() {
    const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    let res = "";
    for (let i = 0; i < 32; i++) {
      res += chars.charAt(Math.floor(Math.random() * chars.length))
    }
    return res;
  },
  // 小程序下单生成的Authorization签名
  generateAuthSign(bodyString, url = "/v3/pay/transactions/jsapi") {
    const { app } = this;

    const timestamps = Math.floor(new Date().getTime() / 1000);
    const nonceStr = crypto.randomBytes(16).toString("hex");
    // 生成待签名
    const waitSign = `POST\n${url}\n${timestamps}\n${nonceStr}\n${bodyString}\n`;
    // 计算签名值（使用sha256签名）
    const sign = crypto.createSign("SHA256")
    sign.update(waitSign)
    const signature = sign.sign(privateKey, "base64");

    return `WECHATPAY2-SHA256-RSA2048 mchid="${app.config.wx.mchid}",nonce_str="${nonceStr}",signature="${signature}",timestamp="${timestamps}",serial_no="${app.config.wx.serial_no}"`
  },
  // 生成小程序支付需要的paySign签名
  generatePaySign(prepay_id) {
    const { app } = this;

    const timestamps = Math.floor(new Date().getTime() / 1000);
    const nonceStr = crypto.randomBytes(16).toString("hex");
    // 生成待签名
    const waitSign = `${app.config.wx.appid}\n${timestamps}\n${nonceStr}\nprepay_id=${prepay_id}\n`;
    // 计算签名值（使用sha256签名）
    const sign = crypto.createSign("SHA256")
    sign.update(waitSign)
    const paySign = sign.sign(privateKey, "base64");
    return {
      timeStamp: String(timestamps),
      nonceStr,
      package:`prepay_id=${prepay_id}`,
      signType: "RSA",
      paySign
    }
  }
}